<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="数据库名称" prop="dbName">
        <el-input
          v-model="queryParams.dbName"
          placeholder="请输入数据库名称"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="备份周期" prop="backupCycle">
        <el-select v-model="queryParams.backupCycle" placeholder="请选择备份周期" clearable>
          <el-option label="每天" value="1" />
          <el-option label="每周" value="2" />
          <el-option label="每月" value="3" />
        </el-select>
      </el-form-item>
      <el-form-item label="状态" prop="scheduleBackup">
        <el-select v-model="queryParams.scheduleBackup" placeholder="请选择状态" clearable>
          <el-option label="启用" value="1" />
          <el-option label="停用" value="0" />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="el-icon-video-play"
          size="mini"
          :disabled="single"
          @click="handleExecute"
          v-hasPermi="['system:backup:execute']"
        >执行备份</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-video-play"
          size="mini"
          :disabled="multiple"
          @click="handleBatchExecute"
          v-hasPermi="['system:backup:execute']"
        >批量执行</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['system:backup:remove']"
        >批量删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
          v-hasPermi="['system:backup:export']"
        >导出</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="backupTaskList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="数据库名称" align="center" prop="dbName" />
      <el-table-column label="数据库类型" align="center" prop="dbType">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.sys_db_type" :value="scope.row.dbType"/>
        </template>
      </el-table-column>
      <el-table-column label="所属服务器" align="center" prop="serverName" />
      <el-table-column label="备份周期" align="center" prop="backupCycle">
        <template slot-scope="scope">
          <span v-if="scope.row.backupCycle === '1'">每天</span>
          <span v-else-if="scope.row.backupCycle === '2'">每周</span>
          <span v-else-if="scope.row.backupCycle === '3'">每月</span>
          <span v-else>-</span>
        </template>
      </el-table-column>
      <el-table-column label="备份时间" align="center" prop="backupTime" />
      <el-table-column label="备份方式" align="center">
        <template slot-scope="scope">
          <el-tag v-if="scope.row.backupServerId" type="warning">远程备份</el-tag>
          <el-tag v-else type="info">本地备份</el-tag>
        </template>
      </el-table-column>
      <el-table-column label="上次备份时间" align="center" prop="lastBackupTime" width="180">
        <template slot-scope="scope">
          <span v-if="scope.row.lastBackupTime">{{ parseTime(scope.row.lastBackupTime) }}</span>
          <span v-else class="text-muted">暂无备份记录</span>
        </template>
      </el-table-column>
      <el-table-column label="状态" align="center" prop="scheduleBackup">
        <template slot-scope="scope">
          <el-switch
            v-model="scope.row.scheduleBackup"
            active-value="1"
            inactive-value="0"
            @change="handleStatusChange(scope.row)"
          ></el-switch>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-view"
            @click="handleView(scope.row)"
            v-hasPermi="['system:backup:query']"
          >查看</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['system:backup:edit']"
          >修改</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-video-play"
            @click="handleExecute(scope.row)"
            v-hasPermi="['system:backup:execute']"
          >执行</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['system:backup:remove']"
          >删除</el-button>
        </template>
      </el-table-column>
    </el-table>
    
    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 备份任务详情对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="600px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="100px">
        <el-row>
          <el-col :span="12">
            <el-form-item label="数据库名称">
              <el-input v-model="form.dbName" disabled />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="数据库类型">
              <el-select v-model="form.dbType" disabled>
                <el-option
                  v-for="dict in dict.type.sys_db_type"
                  :key="dict.value"
                  :label="dict.label"
                  :value="dict.value"
                />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="所属服务器">
              <el-input v-model="form.serverName" disabled />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="启用定时备份" prop="scheduleBackup">
              <el-radio-group v-model="form.scheduleBackup">
                <el-radio label="1">启用</el-radio>
                <el-radio label="0">停用</el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>
        </el-row>
        
        <div v-if="form.scheduleBackup === '1'">
          <el-row>
            <el-col :span="12">
              <el-form-item label="备份周期" prop="backupCycle">
                <el-radio-group v-model="form.backupCycle">
                  <el-radio label="1">每天</el-radio>
                  <el-radio label="2">每周</el-radio>
                  <el-radio label="3">每月</el-radio>
                </el-radio-group>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="备份时间" prop="backupTime">
                <el-time-picker
                  v-model="backupTimeValue"
                  format="HH:mm"
                  value-format="HH:mm"
                  placeholder="选择时间"
                  @change="handleTimeChange"
                ></el-time-picker>
              </el-form-item>
            </el-col>
          </el-row>
          
          <el-form-item label="备份方式" prop="backupMethod">
            <el-radio-group v-model="form.backupMethod">
              <el-radio label="local">本地备份</el-radio>
              <el-radio label="remote">远程备份</el-radio>
            </el-radio-group>
          </el-form-item>
          
          <div v-if="form.backupMethod === 'remote'">
            <el-form-item label="备份服务器" prop="backupServerId">
              <el-select v-model="form.backupServerId" placeholder="请选择备份服务器">
                <el-option
                  v-for="server in serverOptions"
                  :key="server.serverId"
                  :label="server.serverName"
                  :value="server.serverId"
                />
              </el-select>
            </el-form-item>
            
            <el-form-item label="备份路径" prop="backupPath">
              <el-input v-model="form.backupPath" placeholder="请输入备份路径" />
            </el-form-item>
          </div>
        </div>
        
        <el-form-item label="上次备份时间">
          <el-input v-model="lastBackupTimeText" disabled />
        </el-form-item>
        
        <el-form-item label="备注" prop="remark">
          <el-input v-model="form.remark" type="textarea" placeholder="请输入内容" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm" v-if="!isView">确 定</el-button>
        <el-button @click="cancel">{{ isView ? '关 闭' : '取 消' }}</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { listBackupTask, getBackupTask, updateBackupTask, changeBackupTaskStatus, executeBackupTask, batchExecuteBackupTask, exportBackupTask, delBackupTask } from "@/api/system/backupTask";
import { listServerOptions } from "@/api/datasync/server";
import { parseTime } from '@/utils/ruoyi';

export default {
  name: "BackupTask",
  dicts: ['sys_db_type'],
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 备份任务表格数据
      backupTaskList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 是否为查看模式
      isView: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        dbName: null,
        backupCycle: null,
        scheduleBackup: null
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        scheduleBackup: [
          { required: true, message: "请选择是否启用定时备份", trigger: "change" }
        ],
        backupCycle: [
          { required: true, message: "请选择备份周期", trigger: "change" }
        ],
        backupTime: [
          { required: true, message: "请选择备份时间", trigger: "change" }
        ],
        backupMethod: [
          { required: true, message: "请选择备份方式", trigger: "change" }
        ],
        backupServerId: [
          { required: true, message: "请选择备份服务器", trigger: "change" }
        ],
        backupPath: [
          { required: true, message: "请输入备份路径", trigger: "blur" }
        ]
      },
      // 服务器选项
      serverOptions: [],
      // 备份时间值
      backupTimeValue: null
    };
  },
  computed: {
    lastBackupTimeText() {
      return this.form.lastBackupTime ? parseTime(this.form.lastBackupTime) : '暂无备份记录';
    }
  },
  created() {
    this.getList();
    this.getServerOptions();
  },
  methods: {
    parseTime,
    /** 查询备份任务列表 */
    getList() {
      this.loading = true;
      listBackupTask(this.queryParams).then(response => {
        this.backupTaskList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    /** 获取服务器选项 */
    getServerOptions() {
      listServerOptions().then(response => {
        this.serverOptions = response.data;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        dbId: null,
        dbName: null,
        dbType: null,
        serverName: null,
        scheduleBackup: "1",
        backupCycle: "1",
        backupTime: null,
        backupMethod: "local",
        backupServerId: null,
        backupPath: null,
        lastBackupTime: null,
        remark: null
      };
      this.backupTimeValue = null;
      this.isView = false;
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.dbId)
      this.single = selection.length!==1
      this.multiple = !selection.length
    },
    /** 查看按钮操作 */
    handleView(row) {
      this.reset();
      this.isView = true;
      const dbId = row.dbId || this.ids[0];
      getBackupTask(dbId).then(response => {
        this.form = response.data;
        this.form.backupMethod = this.form.backupServerId ? 'remote' : 'local';
        this.backupTimeValue = this.form.backupTime;
        this.open = true;
        this.title = "查看备份任务";
      });
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      this.isView = false;
      const dbId = row.dbId || this.ids[0];
      getBackupTask(dbId).then(response => {
        this.form = response.data;
        this.form.backupMethod = this.form.backupServerId ? 'remote' : 'local';
        this.backupTimeValue = this.form.backupTime;
        this.open = true;
        this.title = "修改备份任务";
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          // 处理备份方式
          if (this.form.backupMethod === 'local') {
            this.form.backupServerId = null;
            this.form.backupPath = null;
          }

          updateBackupTask(this.form).then(response => {
            this.$modal.msgSuccess("修改成功");
            this.open = false;
            this.getList();
          });
        }
      });
    },
    /** 状态修改 */
    handleStatusChange(row) {
      let text = row.scheduleBackup === "1" ? "启用" : "停用";
      this.$modal.confirm('确认要"' + text + '""' + row.dbName + '"的定时备份吗？').then(function() {
        return changeBackupTaskStatus({
          dbId: row.dbId,
          scheduleBackup: row.scheduleBackup
        });
      }).then(() => {
        this.$modal.msgSuccess(text + "成功");
        this.getList();
      }).catch(function() {
        row.scheduleBackup = row.scheduleBackup === "0" ? "1" : "0";
      });
    },
    /** 执行备份操作 */
    handleExecute(row) {
      const dbIds = row ? [row.dbId] : this.ids;
      const dbNames = row ? [row.dbName] : this.backupTaskList.filter(item => this.ids.includes(item.dbId)).map(item => item.dbName);

      if (dbIds.length === 1) {
        this.$modal.confirm('确认要执行数据库"' + dbNames[0] + '"的备份任务吗？').then(() => {
          this.$modal.loading("正在执行备份，请稍候...");
          return executeBackupTask(dbIds[0]);
        }).then((response) => {
          this.$modal.closeLoading();
          this.$modal.msgSuccess(response.msg);
          this.getList();
        }).catch(() => {
          this.$modal.closeLoading();
        });
      }
    },
    /** 批量执行备份操作 */
    handleBatchExecute() {
      if (this.ids.length === 0) {
        this.$modal.msgError("请选择要执行备份的数据库");
        return;
      }

      const dbNames = this.backupTaskList.filter(item => this.ids.includes(item.dbId)).map(item => item.dbName);
      this.$modal.confirm('确认要批量执行选中的 ' + this.ids.length + ' 个数据库的备份任务吗？\n数据库：' + dbNames.join('、')).then(() => {
        this.$modal.loading("正在批量执行备份，请稍候...");
        return batchExecuteBackupTask(this.ids);
      }).then((response) => {
        this.$modal.closeLoading();
        if (response.code === 200) {
          this.$modal.msgSuccess(response.msg);
        } else {
          this.$modal.msgWarning(response.msg);
        }
        this.getList();
      }).catch(() => {
        this.$modal.closeLoading();
      });
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('system/backup/task/export', {
        ...this.queryParams
      }, `backup_task_${new Date().getTime()}.xlsx`)
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const dbIds = row ? [row.dbId] : this.ids;
      const dbNames = row ? [row.dbName] : this.backupTaskList.filter(item => this.ids.includes(item.dbId)).map(item => item.dbName);

      if (dbIds.length === 1) {
        this.$modal.confirm('确认要删除数据库"' + dbNames[0] + '"的备份任务吗？删除后将停止定时备份并清除备份配置。').then(() => {
          return delBackupTask(dbIds);
        }).then((response) => {
          this.$modal.msgSuccess(response.msg);
          this.getList();
        }).catch(() => {});
      } else {
        this.$modal.confirm('确认要删除选中的 ' + dbIds.length + ' 个备份任务吗？\n数据库：' + dbNames.join('、') + '\n删除后将停止定时备份并清除备份配置。').then(() => {
          return delBackupTask(dbIds);
        }).then((response) => {
          this.$modal.msgSuccess(response.msg);
          this.getList();
        }).catch(() => {});
      }
    },
    /** 处理备份时间变化 */
    handleTimeChange(time) {
      this.form.backupTime = time;
    }
  }
};
</script>
